package service

import (
	"dataaysn/internal/model"
	"dataaysn/internal/repository"

	"github.com/gin-gonic/gin"
)

type CollectionService struct {
	repo repository.CollectionRepository
}

func NewCollectionService(repo repository.CollectionRepository) *CollectionService {
	return &CollectionService{repo: repo}
}

func (s *CollectionService) CreateCollection(c *gin.Context) {
	var config model.CollectionConfig
	if err := c.ShouldBindJSON(&config); err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}

	if err := s.repo.CreateCollection(&config); err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}

	c.JSON(200, config)
}

func (s *CollectionService) GetCollection(c *gin.Context) {
	id := c.Param("id")
	config, err := s.repo.GetCollection(id)
	if err != nil {
		c.JSON(404, gin.H{"error": "not found"})
		return
	}
	c.JSON(200, config)
}

func (s *CollectionService) UpdateCollection(c *gin.Context) {
	var config model.CollectionConfig
	if err := c.ShouldBindJSON(&config); err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}

	if err := s.repo.UpdateCollection(&config); err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}

	c.JSON(200, config)
}

func (s *CollectionService) DeleteCollection(c *gin.Context) {
	id := c.Param("id")
	if err := s.repo.DeleteCollection(id); err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}
	c.JSON(200, gin.H{"message": "deleted"})
}

func (s *CollectionService) ListCollections(c *gin.Context) {
	configs, err := s.repo.ListCollections()
	if err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}
	c.JSON(200, configs)
}

func (s *CollectionService) TestDBConnection(c *gin.Context) {
	var conn model.DBConnection
	if err := c.ShouldBindJSON(&conn); err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}

	// 测试数据库连接逻辑
	if err := s.repo.TestConnection(&conn); err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}

	c.JSON(200, gin.H{"message": "connection successful"})
}

func (s *CollectionService) TestSSHConnection(c *gin.Context) {
	var sshConfig model.SSHConfig
	if err := c.ShouldBindJSON(&sshConfig); err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}

	// 测试SSH连接逻辑
	if err := s.repo.TestSSHConnection(&sshConfig); err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}

	c.JSON(200, gin.H{"message": "SSH connection successful"})
}
